package com.lc.service.impl;

import com.cnpc.framework.base.entity.BaseResponse;
import com.cnpc.framework.base.service.impl.BaseServiceImpl;
import com.lc.entity.Msg;
import com.lc.entity.MsgRelation;
import com.lc.service.MsgService;
import com.lc.service.UtilService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 下雨不带伞 on 2020/9/7.
 */
@Service
public class MsgServiceImpl extends BaseServiceImpl implements MsgService {

    @Autowired
    UtilService utilService;

    @Override
    public BaseResponse editMsg(Msg msg) throws Exception {
        BaseResponse response = new BaseResponse();

        Integer id = msg.getId();
        String userID = msg.getUserID();
        if (id==null) {
            msg.setDefaultTime();
            response = utilService.setUserInfo(userID,msg,null);
            if (response.getStatus()!=0) {
                return response;
            }

            save(msg);
            id = msg.getId();
        }else {
            Msg oldMsg = get(Msg.class, id);
            String oldUserId = oldMsg.getUserID();
                response = utilService.setUserInfo(userID,msg,null);
                if (response.getStatus()!=0) {
                    return response;
                }


            BeanUtils.copyProperties(msg, oldMsg, "create_date_time");
            oldMsg.setDefaultUpdateTime();
            msg = oldMsg;
            update(msg);
        }

        response.setStatus(1);
        return response;
    }

    @Override
    public BaseResponse getMsgList(String userId, String keyword, String status, String startTime, String endTime, Integer pageNum, Integer pageSize) throws Exception {
        BaseResponse response = new BaseResponse();
        String cntsql = " select count(*) from t_msg m where";
        String sql = " select m.*,d.name msgTypeText from t_msg m " +
                " left join tbl_dict d on d.code = m.msgType " +
                " where";

        StringBuilder whereClause = new StringBuilder();
        Map<String, Object> params = new HashMap<>();

        if (StringUtils.isNotEmpty(userId)) {
            whereClause.append("and  m.userID = :userId").append(" ");
            params.put("userId", userId);
        }

        if (StringUtils.isNotEmpty(keyword)) {
            whereClause.append("and  (m.userName like :keyword or m.title like :keyword or m.content like :keyword)").append(" ");
            params.put("keyword", "%" + keyword + "%");

        }

        if (StringUtils.isNotEmpty(status)) {
            whereClause.append("and  m.status = :status").append(" ");
            params.put("status", status);
        }

        if (StringUtils.isNotEmpty(startTime)) {

            whereClause.append("and  m.create_date_time >= :startTime").append(" ");
            params.put("startTime", startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            if (endTime.length() == 10) {
                endTime += " 23:59:59";
            }
            whereClause.append("and m.create_date_time <= :endTime").append(" ");
            params.put("endTime", endTime);
        }
        if (whereClause.length() > 0) {
            cntsql += whereClause.substring(3, whereClause.length());
            sql += whereClause.substring(3, whereClause.length());
        } else {
            cntsql = cntsql.replace("where", "");
            sql = sql.replace("where", "");
        }
        sql += " order by m.create_date_time desc";
        Long cnt = countBySql(cntsql, params);
        List<Map<String, Object>> dataList = null;

        if (cnt > 0 && pageSize != null && pageSize > 0 && pageNum != null && pageNum > 0) {
            dataList = findMapBySql(sql, params, pageNum, pageSize);
        } else {
            dataList = findMapBySql(sql, params);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("count", cnt);
        data.put("list", dataList);
        response.setStatus(1);
        response.setData(data);
        return response;
    }

    @Override
    public BaseResponse getAppMsgList(String userId, String keyword, String status, String startTime, String endTime, Integer pageNum, Integer pageSize) throws Exception {
        BaseResponse response = new BaseResponse();
        String cntsql = " select count(*) from t_msg m " +
                " left join (select * from t_msg_relation where userId = :userId)  mr on mr.msgId = m.id where";
        String sql = " select m.*,d.name msgTypeText,case when mr.status=1 then 1 else 0 end readStatus from t_msg m " +
                " left join (select * from t_msg_relation where userId = :userId)  mr on mr.msgId = m.id " +
                " left join tbl_dict d on d.code = m.msgType " +
                " where";

        StringBuilder whereClause = new StringBuilder();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);

        if (StringUtils.isNotEmpty(keyword)) {
            whereClause.append("and  (m.userName like :keyword or m.title like :keyword or m.content like :keyword)").append(" ");
            params.put("keyword", "%" + keyword + "%");

        }

        if ("1".equals(status)) {
            whereClause.append("and  rm.status = 1").append(" ");
        }else if ("0".equals(status)) {
            whereClause.append("and  (rm.status = 0 or rm.status is null)").append(" ");
        }

        if (StringUtils.isNotEmpty(startTime)) {

            whereClause.append("and  m.create_date_time >= :startTime").append(" ");
            params.put("startTime", startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            if (endTime.length() == 10) {
                endTime += " 23:59:59";
            }
            whereClause.append("and m.create_date_time <= :endTime").append(" ");
            params.put("endTime", endTime);
        }
        if (whereClause.length() > 0) {
            cntsql += whereClause.substring(3, whereClause.length());
            sql += whereClause.substring(3, whereClause.length());
        } else {
            cntsql = cntsql.substring(0,cntsql.length()-5);
            sql = sql.substring(0,sql.length()-5);
        }
        sql += " order by m.create_date_time desc";
        Long cnt = countBySql(cntsql, params);
        List<Map<String, Object>> dataList = null;

        if (cnt > 0 && pageSize != null && pageSize > 0 && pageNum != null && pageNum > 0) {
            dataList = findMapBySql(sql, params, pageNum, pageSize);
        } else {
            dataList = findMapBySql(sql, params);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("count", cnt);
        data.put("list", dataList);
        response.setStatus(1);
        response.setData(data);
        return response;
    }

    @Override
    public BaseResponse updateAndGetMsg(Integer msgId, String userId) throws Exception {
        BaseResponse response = new BaseResponse();
        String sql = " select m.*,d.name msgTypeText from t_msg m " +
                " left join tbl_dict d on d.code = m.msgType " +
                " where m.id = :msgId";
        Map<String, Object> params = new HashMap<>();
        params.put("msgId", msgId);
        Map<String, Object> data = getMapBySql(sql, params);
        if (data == null) {
            response.setStatus(2);
            response.setMessage("对象不存在！");
            return response;
        }
        sql = "select * from t_msg_relation mr where mr.userId= :userId and msgId = :msgId";
        params.put("userId", userId);
        MsgRelation msgRelation = getBySql(sql, params, MsgRelation.class);
        if (msgRelation == null) {
            msgRelation = new MsgRelation();
            msgRelation.setDefaultTime();
            msgRelation.setMsgId(msgId);
            msgRelation.setUserId(userId);
            msgRelation.setStatus(1);
            save(msgRelation);
        }
        response.setStatus(1);
        response.setData(data);
        return response;
    }

    @Override
    public BaseResponse deleteMsg(String msgId) throws Exception {
        BaseResponse response = new BaseResponse();
        String sql = " select m.*  from t_msg m " +
                "  where m.id = :msgId";
        Map<String, Object> params = new HashMap<>();
        params.put("msgId", msgId);
        Msg root = getBySql(sql, params, Msg.class);
        if (root == null) {
            response.setStatus(2);
            response.setMessage("对象不存在！");
            return response;
        }
        delete(root);
        response.setStatus(1);
        return response;
    }
}
